package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 1、每天营业额统计(指定日期区间)
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.使用集合存放区间内每天的日期值
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //循环添加区间内日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //2.使用集合存放区间内日期对应的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询该日期间的营业额数据(营业额指已完成状态的订单金额总和)
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN); //日期加上时刻
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询条件使用Map存放
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            //判断该日是否无营业额(因为sum函数查不到时为null)
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //3.将集合数据拼接为“，”分隔的字符串，封装进VO对象返回
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return turnoverReportVO;
    }

    /**
     * 2、总用户及新用户数量统计(指定日期区间)
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.使用集合存放区间内每天的日期值
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //循环添加区间内日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //2.使用集合存放区间内日期对应的总用户数、新用户数
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        //3.查询区间内每日的总用户数、新用户数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            //查总用户数
            Integer totalUser = userMapper.countByMap(map);
            //count函数查不到时，为0，不为null
            totalUserList.add(totalUser);

            //查新用户数
            map.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
        }

        //4.将集合数据拼接为“，”分隔的字符串，封装进VO对象返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 3、订单分析统计(指定日期区间)
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.使用集合存放区间内每天的日期值
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //2.每日订单数集合与每日有效订单数集合
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        //3.查询每日订单数与每日有效订单数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            //查询每日订单数
            Integer orderCount = orderMapper.countByMap(map);
            orderCountList.add(orderCount);
            //查询每日有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);
        }

        //4.计算订单总数、有效订单总数、订单完成率
        Integer totalOrderCount = 0;
        for (Integer integer : orderCountList) {
            totalOrderCount += integer;
        }
        Integer totalValidOrderCount = 0;
        for (Integer integer : validOrderCountList) {
            totalValidOrderCount += integer;
        }
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = totalValidOrderCount.doubleValue() / totalOrderCount;
        }

        //5.将集合数据拼接为“，”分隔的字符串，封装进VO对象返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ",")) //日期
                .orderCountList(StringUtils.join(orderCountList, ",")) //每日订单数
                .validOrderCountList(StringUtils.join(validOrderCountList, ",")) //每日有效订单数
                .totalOrderCount(totalOrderCount) //订单总数
                .validOrderCount(totalValidOrderCount) //有效订单总数
                .orderCompletionRate(orderCompletionRate) //订单完成率
                .build();
    }

    /**
     * 4、查询销量排名top10(指定日期区间)
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //时间区间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //1.查询出时间区间内销量排名前十商品的名称和销量
        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.getSalesTop10(beginTime, endTime);

        //2.使用list集合存放商品名称和销量
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }

        //3.将集合数据拼接为“，”分隔的字符串，封装进VO对象返回
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出运营数据Excel报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //时间区间为此前30天
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().plusDays(-1);

        //1.查询出此前30天运营数据
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        //2.通过POI将运营数据写入Excel文件
        //以输入流的形式加载Excel模板文件
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(is);
            //获取sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充第二行第二格---时间区间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginDate + "至" + endDate);

            //填充第4行概览数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //填充第5行概览数据
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充从第8行开始的30天明细数据
            for (int i = 0; i < 30; i++) {
                //查询数据
                LocalDate date = beginDate.plusDays(i);
                LocalDateTime begin = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
                businessData = workspaceService.getBusinessData(begin, end);
                //填充数据
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3.通过输出流将Excel文件下载到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //4.关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
